<?php 
/* 
 * This file is part of TCDB. 
 * 
 * Copyright (C) 2000-2009 
 * Technology Consultant Corps 
 * Grinnell College 
 * Grinnell, IA, 50112 
 * tc@grinnell.edu 
 * 
 * TCDB is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * TCDB is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with TCDB. If not, see <http://www.gnu.org/licenses/>. 
 * 
 
 ============================================================================= 
 
 * init.php -- Opens a connection to the MySQL database
 *	       If we receive username and password info in the $_POST array,
 *             check for the user_id, rank_id, and priveleges of user to
 *             which the credentials correspond and store info in a session
 * 
 * Author: Dylan J. Sather
 * Created: 2009-06-04 
 * Last edited: 2009-07-23
 *
 * Thanks to Andrew Kensler, Paul Heider, James Michael-Hill, and Avram Lyon
 * for their work on init.php since September 2000
 */ 

// Get configuration settings and functions; start session
require 'config.php';
require 'functions.php';

session_set_cookie_params(0,'/','tcdb.ath.cx');
session_start();

// To start, $user_id is empty
$user_id = '';

// Establish a connection to the DB by instantiating a mysqli object
$mysqli = new mysqli($config['mysql_host'], $config['mysql_user'], $config['mysql_passwd'], $config['mysql_db']);

/* Check to see if there were any errors in connecting; if so, print a message to users
   and e-mail the TCDB admins, as well */
if (mysqli_connect_errno()) {
    
    print "Sorry -- it looks like TCDB is having trouble connecting to the database. <br />
           Please contact " . $config["tcdb_admin_email"] . " and let them know";
    $to = $config["tcdb_admin_email"];
    $subject = "TCDB connection error";
    $message = "TCDB had an error in connecting to the DB: " . mysqli_connect_error();

    mail($to, $subject, $message);

    exit();
}

// If we have both a username and password, and if neither is empty, this is a login attempt
if ((isset($_POST['login_username']) && isset($_POST['login_password']))
     && $_POST['login_username'] != '' && $_POST['login_password'] != '') {

    // Look up the user ID that corresponds to the username (and escape strings)
    $query = sprintf("SELECT id, username, password
                      FROM users
	              WHERE username = '%s'
	              AND password = sha1('%s')",
		  mysqli_real_escape_string($mysqli, $_POST['login_username']),
		  mysqli_real_escape_string($mysqli, $_POST['login_password']));

    $result = $mysqli->query($query, MYSQLI_STORE_RESULT);

    list($user_id, $username, $user_password) = $result->fetch_row();

    $result->free();

    // Set session information; ensure that $user_id is set and is numeric
    if (isset($user_id) && is_numeric($user_id)) {
	$_SESSION['user_id'] = $user_id;
	$_SESSION['username'] = $username;
	$_SESSION['user_password'] = $user_password;
    }

    // If this was a successful login, set last_login time
    if (isset($_SESSION['user_id'])) {
	$query = sprintf("UPDATE users SET last_login = NOW()
			  WHERE id = '%s'",
		      mysqli_real_escape_string($mysqli, $_SESSION['user_id']));
	
	$mysqli->query($query);
    }

    // Now, get rank info for this user
    $rank_id = 0;
    $query = sprintf("SELECT rank_id 
		      FROM users
		      WHERE id='%s'",
		  mysqli_real_escape_string($mysqli, $user_id));

    $result = $mysqli->query($query, MYSQLI_STORE_RESULT);

    list($rank_id) = $result->fetch_row();

    $result->free();

    // And set the session info accordingly
    if (isset($rank_id) && is_numeric($rank_id)) {
	$_SESSION['rank_id'] = $rank_id;
    }

    /* See if this user is a new user. A user will be a new user only if
       an admin has created an account for this user and it's her first
       time logging in */
    $new_user = FALSE;
    $query = sprintf("SELECT new_user 
		      FROM users
		      WHERE id='%s'",
		  mysqli_real_escape_string($mysqli, $user_id));

    $result = $mysqli->query($query, MYSQLI_STORE_RESULT);

    list($new_user) = $result->fetch_row();

    $result->free();
    
    $_SESSION['new_user'] = $new_user;

    // Finally, set priveleges based on rank
    $is_full_TC = FALSE;
    $is_admin = FALSE;
    $query = sprintf("SELECT is_full_TC, is_admin
		      FROM ranks
		      WHERE id='%s'",
		  mysqli_real_escape_string($mysqli, $rank_id));

    $result = $mysqli->query($query, MYSQLI_STORE_RESULT);

    list($is_full_TC, $is_admin) = $result->fetch_row();

    $result->free();

    $_SESSION['is_full_TC'] = $is_full_TC;
    $_SESSION['is_admin'] = $is_admin;

    
    // If we have a new user, redirect to update_info.php so she can update her info
    if ($_SESSION['new_user']) {
	header('Location: update_info.php');
    }
}

?>
